<template>
  <div>
    <el-dialog
      v-if="attrs.flowOptions && attrs.flowOptions.length > 1"
      v-model="dialogFormVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="选择流程"
      width="800"
      @close="handleClose"
    >
      <el-table :data="attrs.flowOptions" fit>
        <el-table-column label="序号" type="index" width="50"></el-table-column>
        <el-table-column
          :show-overflow-tooltip="true"
          label="流程标识"
          prop="processKey"
        />
        <el-table-column
          :show-overflow-tooltip="true"
          label="流程名称"
          prop="processName"
        >
        </el-table-column>
        <el-table-column
          align="center"
          class-name="small-padding fixed-width"
          label="操作"
        >
          <template #default="scope">
            <!-- v-hasPermi="['workflow:process:start']" -->
            <el-button
              icon="el-icon-video-play"
              text
              type="primary"
              @click="handleStart(scope.row)"
              >发起
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!--流程表单-->
    <el-dialog
      v-model="returnOpen"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="returnTitle"
      width="40%"
      @close="clearForm"
    >
      <el-form
        ref="taskForm"
        :model="taskHand"
        :rules="rules"
        label-width="140px"
      >
        <el-form-item label="下一环节：" prop="taskName">
          <el-input v-model="taskHand.taskName" disabled type="input" />
        </el-form-item>
        <el-form-item label="下一环节处理人：" prop="nextUserIdsUUID">
          <el-select
            v-model="taskHand.nextUserIdsUUID"
            :disabled="taskHand.isSelset"
            class="w-full"
            clearable
            multiple
            placeholder="请选择下一环节处理人"
            @focus="userInputFocus('nextUserIds')"
          >
            <el-option
              v-for="(item, index) in selectOptionObj['nextUserIds']"
              :key="index"
              :label="item.label"
              :value="item.uuid"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="抄送：" prop="copyUserIdsUUID">
          <el-select
            v-model="taskHand.copyUserIdsUUID"
            class="w-full"
            clearable
            filterable
            multiple
            placeholder="请选择抄送"
            @focus="userInputFocus('copyUserIds')"
          >
            <el-option
              v-for="(item, index) in selectOptionObj['copyUserIds']"
              :key="index"
              :label="item.label"
              :value="item.uuid"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="footer dialog-footer text-right">
        <el-button @click="clearForm('clear')">取 消</el-button>
        <el-button :loading="btnLoading" type="primary" @click="submitReturn"
          >确 定
        </el-button>
      </div>
    </el-dialog>
    <!-- 弹出框选择人员 下拉框 -->
    <SelectDialog
      :dialog-param="dialogParamUse"
      @close="closeFn"
      @ok="selectDialogData"
    ></SelectDialog>
  </div>
</template>
<script name="SubmissionProcess" setup>
import { reactive, getCurrentInstance, watchEffect } from 'vue'
import { getDeptStaffTreeData } from '@/api/system/dept'
import {
  getPricipalId,
  getTreeNodeByParam,
  getUniqueUserId
} from '@/utils/commo'
import useCommonStore from '@/store/modules/common'
import { firstUserTaskHasUser } from '@/api/workflow/model'
import { listProcess, getBpmnXml, startProcess } from '@/api/workflow/process'
import WorkProcess from '@/views/workflow/work/index.vue'

const { proxy } = getCurrentInstance()
const commonStore = useCommonStore()
const attrs = useAttrs() //接受不走props的参数
const btnLoading = ref(false) //按钮加载状态
const props = defineProps({
  dialogParam: {
    required: true,
    type: Object || Array,
    default: () => {
      return {}
    }
  }
})
const dialogFormVisible = ref(false)
const data = reactive({
  taskHand: { nextUserIdsUUID: [] },
  rules: {
    taskName: [{ required: true, message: '', trigger: ['blur', 'change'] }],
    nextUserIdsUUID: [
      {
        required: true,
        message: '下一环节处理人不能为空',
        trigger: ['blur', 'change']
      }
    ]
  },
  returnTitle: null,
  returnOpen: false,
  flowUseData: [] //下一环节处理人
})
const { taskHand, rules, returnTitle, returnOpen, flowUseData } = toRefs(data)
watch(
  () => props.dialogParam,
  val => {
    console.log(val, props.dialogParam.visible, 'attrs.flowOptions.length')
    if (!props.dialogParam.visible || props.dialogParam.visible == false) {
      return false
    }
    dialogFormVisible.value = props.dialogParam.visible
    console.log(dialogFormVisible.value)
    console.log(attrs.flowOptions.length, 'attrs.flowOptions.length')
    if (attrs.flowOptions.length == 1) {
      handleStart({ definitionId: attrs.flowOptions[0].definitionId })
    }
  },
  {
    deep: true
  }
)

/**** 流程模块 start */

/** 流程弹出框 确认按钮 */
function submitReturn() {
  proxy.$refs['taskForm'].validate(valid => {
    if (valid) {
      if (
        JSON.stringify(taskHand.value.nextUserIdsUUID) == '[]' ||
        !taskHand.value.nextUserIdsUUID
      ) {
        proxy.$modal.msgError('下一环节处理人不能为空')
        return false
      }
      btnLoading.value = true
      let newParams = {}
      newParams.businessId = props.dialogParam.businessId //业务id
      newParams.nextUserIds = taskHand.value.nextUserIds
      newParams.copyUserIds = taskHand.value.copyUserIds
      newParams.messageTitle = props.dialogParam.businessName //业务名称
      newParams.categoryCode = props.dialogParam.categoryCode //分类编码：项目1，订单2 客户3 	投标4
      newParams.appointUserId = props.dialogParam.appointUserId || null //环节中有指定用户
      newParams.appointUserName = props.dialogParam.appointUserName || null //环节中有指定用户
      if (newParams.categoryCode === '26' || newParams.categoryCode === '27') {
        // 工单流程添加参数 -- 是否部门经理
        newParams.isLeader = props.dialogParam.isLeader
      }
      //传递给发起接口的特殊参数
      const result =
        props.dialogParam.initiateParams &&
        JSON.stringify(props.dialogParam.initiateParams) != '{}'
          ? Object.assign(newParams, props.dialogParam.initiateParams)
          : newParams

      console.log(
        props.dialogParam.initiateParams,
        'props.dialogParam.initiateParams'
      )
      startProcess(taskHand.value.definitionId, result)
        .then(res => {
          proxy.$modal.msgSuccess('发起成功')
          dialogFormVisible.value = false
          returnOpen.value = false
          emit('initiate', 'initiate')
          btnLoading.value = false
        })
        .catch(error => {
          btnLoading.value = false
        })
    }
  })
}

function clearForm(type) {
  proxy.resetForm('taskForm')
  taskHand.value = {}
  if (attrs.flowOptions.length == 1) {
    //回主页
    returnOpen.value = false
    dialogFormVisible.value = false
    emit('close', 'examine')
  } else {
    returnOpen.value = false
    dialogFormVisible.value = true
  }
}

/************************** 选择人 模块 start */
const dialogParamUse = ref({})
const selectOptionObj = ref({})

/**
 * 归属人员input获取焦点事件
 */
function userInputFocus(type) {
  dialogParamUse.value = {
    type: type,
    title: '请选择人员',
    dataType: 'person',
    nodeKey: 'uuid',
    multiple: true,
    checkStrictly: false
  }
  if (type == 'nextUserIds' && toRaw(flowUseData.value).length >= 1) {
    //下一个环节处理人-岗位多人的情况下
    dialogParamUse.value.data = flowUseData.value
  }
  if (type == 'copyUserIds') {
    //抄送人
    dialogParamUse.value.apiParams = {
      deptId: 100
    }
  }
  dialogParamUse.value.isDialog = true
  dialogParamUse.value.defaultCheckedKeys =
    type == 'nextUserIds'
      ? taskHand.value.nextUserIdsUUID
      : taskHand.value.copyUserIdsUUID || []
}

/** 弹出框下拉框
 * 项目负责人
 * @param {*} val  selectDialog组件返回的值
 */
const selectDialogData = val => {
  switch (val.type) {
    case 'nextUserIds':
      //下一环节处理人
      selectOptionObj.value['nextUserIds'] = val.selectData
      taskHand.value.nextUserIdsUUID = val.defaultCheckedKeys
        ? val.defaultCheckedKeys
        : null
      taskHand.value.nextUserIds = val.defaultCheckedKeys
        ? getPricipalId(
            selectOptionObj.value['nextUserIds'],
            val.defaultCheckedKeys
          ).toString()
        : null
      break
    case 'copyUserIds':
      //抄送人
      selectOptionObj.value['copyUserIds'] = val.selectData
      taskHand.value.copyUserIdsUUID = val.defaultCheckedKeys
        ? val.defaultCheckedKeys
        : null
      taskHand.value.copyUserIds = val.defaultCheckedKeys
        ? getPricipalId(
            selectOptionObj.value['copyUserIds'],
            val.defaultCheckedKeys
          ).toString()
        : null
      break
  }
}
const closeFn = val => {
  dialogParamUse.value.isDialog = false
}

/************************** 选择人 模块 end */
/**
 * 根据当前用户回填下一环节处理人
 */
async function getDefaultUserInfo(id) {
  if (!id || JSON.stringify(id) == '[]') {
    return false
  }
  let arr = [],
    arrData = []
  let deptUserData = await commonStore.getUseTreeData()
  //获取人员数据
  id.map(item => {
    let res = getTreeNodeByParam(deptUserData, item, 'id', [])
    if (res && res.length > 0) {
      arrData.push(res[0])
      arr.push(res[0].uuid)
    }
  })
  selectOptionObj.value['nextUserIds'] = arrData
  taskHand.value.nextUserIdsUUID = arr
  taskHand.value.nextUserIds = id.toString()
}

// 发起界面回显下一步审批人、任务名称
const firstUserTaskHasUserFn = async id => {
  let params = JSON.parse(JSON.stringify(props.dialogParam))
  delete params.visible //弹出框是否显示
  delete params.businessId //业务id
  delete params.businessName //业务名称（如：项目模块 businessName：项目名称）
  delete params.categoryCode //==>流程分类 页面查看 分类编码：项目1，订单2 客户3 	投标4
  //传递给发起接口的特殊参数
  if (params.initiateParams) {
    delete params.initiateParams
  }

  let res = await firstUserTaskHasUser(id, params)
  taskHand.value.taskName = res.data.taskName //下一环节名称
  //1. 下一环节处理人分析
  if (res.data.hasUser && res.data.hasUser.length > 0) {
    // 1.1 设计模型设置了指定人
    taskHand.value.isSelset = true
    let hasUser = res.data.hasUser.split(',').map(Number)
    await getDefaultUserInfo(hasUser)
  } else if (res.data.postUser) {
    //1.2 设计模型设置了岗位
    let postRes = await getDeptStaffTreeData({
      userIds: res.data.postUser
    }) //获取该岗位下的下一环节处理人
    flowUseData.value = postRes.data
    let postIds = res.data.postUser.split(',')
    if (postIds.length == 1) {
      //如果该岗位下只有一个用户的时候 默认选中
      await getDefaultUserInfo(postIds)
      taskHand.value.isSelset = true
    } else {
      taskHand.value.isSelset = false
    }
  } else {
    //1.3 没有下一环节处理人
    taskHand.value.isSelset = false
  }
}
/**发起按钮 */
const handleStart = async row => {
  returnTitle.value = '发起申请'
  flowUseData.value = []
  //业务流程如果只有一条的话，这个是从业务组件传递过来
  await firstUserTaskHasUserFn(row.definitionId)
  taskHand.value.definitionId = row.definitionId
  returnOpen.value = true
  dialogFormVisible.value = false
}
/**** 流程模块 end */
const emit = defineEmits(['close', 'initiate'])

// 取消
function handleClose() {
  dialogFormVisible.value = false
  emit('close', 'examine')
}
</script>
<style lang="scss" scoped>
:deep div.el-card__body {
  padding: 15px 20px 0px 20px !important;

  .avue-crud__menu {
    min-height: 0;
  }
}
</style>
